package me.chenqiang.tre.expression;

import java.util.function.BiFunction;

import org.apache.commons.lang3.StringUtils;

import me.chenqiang.tre.entity.Card;
import me.chenqiang.tre.entity.Device;

/**
 * 用来表示“是”或“不是”的表达式
 * 
 * 表达式左侧和右侧的属性都是单个字符串。例如用于判断持卡人身份类型是否是某个指定类型。
 * 
 */
public class IsExpression implements Expression {
	public enum Type {
		IS, IS_NOT
	}

	protected Type type;
	protected String propertyName;
	protected BiFunction<Card, Device, String> propertyGetter;
	protected String propertyValue;

	public IsExpression(Type type, String propertyName, BiFunction<Card, Device, String> propertyGetter, String value) {
		super();
		this.type = type;
		this.propertyName = propertyName;
		this.propertyGetter = propertyGetter;
		this.propertyValue = value;
	}

	@Override
	public boolean evaluate(Card card, Device device) {
		switch (this.type) {
		case IS:
			return StringUtils.compare(this.propertyGetter.apply(card, device), propertyValue) == 0;
		case IS_NOT:
			return StringUtils.compare(this.propertyGetter.apply(card, device), propertyValue) != 0;
		default:
			throw new IllegalArgumentException(String.format("错误类型：%s", this.type));
		}
	}

	@Override
	public String getType() {
		return this.type.name();
	}

	@Override
	public String getPropertyName() {
		return this.propertyName;
	}

	@Override
	public String getPropertyValue() {
		return this.propertyValue;
	}
}
